package controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.hibernate.criterion.Restrictions;

import model.entity.product.Category;
import model.entity.product.Product;
import model.entity.product.Theme;

import dao.JPAHiberDAOFactory;
import dao.entity.CategoryDAO;
import dao.entity.ProductDAO;
import dao.entity.ThemeDAO;

public class FilterProduct extends HttpServlet {
	private static final long serialVersionUID = 1L;
           
    public FilterProduct() {
        super();
    }
    
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String type = request.getParameter("type");
		String nameOfType = request.getParameter("nameOfType");
		if(type != null && nameOfType != null) {
			HttpSession session = request.getSession();
			ProductDAO productDAO = JPAHiberDAOFactory.getInstance().getProductDAO();
			
			switch (type) {
			case "theme":
				ThemeDAO themeDAO = JPAHiberDAOFactory.getInstance().getThemeDAO();
				List<Theme> theme1 = themeDAO.findByCriteria(Restrictions.like("name", nameOfType));
				 
				session.setAttribute("filteredList", convertSetToList(theme1.get(0).getProducts()));
				break;
			case "cate":
				CategoryDAO categoryDAO = JPAHiberDAOFactory.getInstance().getCategoryDAO();
				Category cate = categoryDAO.findByID(Integer.parseInt(nameOfType)); 
				List<Product> dsCate = productDAO.findByCriteria(Restrictions.like("category",cate)); 
				
				session.setAttribute("filteredList", dsCate);
				break;
			default:
				break;
			}
			
			response.sendRedirect("shop/DanhSachSanPham.jsp");
		}
		
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

	public <T> List<T> convertSetToList(Set<T> set) {
		ArrayList<T> result = new ArrayList<T>();
		for (T t : set) {
			result.add(t);
		}
		return result;
	}
}
